<template>
  <el-tabs v-model="editableTabsValue" type="border-card" :closable="true" @tab-remove="removeTab" @tab-click="changeTab">
    <el-tab-pane
        :key="item.name"
        v-for="item in editableTabs"
        :label="item.title"
        :name="item.name"
    >
      <router-view></router-view>
    </el-tab-pane>
  </el-tabs>
</template>

<script>

export default {
    name: "TabC",
    data() {
        return {

            }
    },
    computed: {
        editableTabs:{
            get() {
                return this.$store.state.editableTabs;
            },
            set(value) {
              this.$store.state.editableTabs = value;
            }
        },
        editableTabsValue: {
            get() {
                return this.$store.state.editableTabsValue;
            },
            set(value) {
                this.$store.state.editableTabsValue = value;
            }
        }
    },
    methods:{
      removeTab(targetName) {
        let tabs = this.editableTabs;
        let activeName = this.editableTabsValue;
        let activeLabel = "";
        if (activeName === targetName) {
          tabs.forEach((tab, index) => {
            if (tab.name === targetName) {
              let nextTab = tabs[index + 1] || tabs[index - 1];
              if (nextTab) {
                activeName = nextTab.name;
                activeLabel = nextTab.title;
              }
            }
          });
        }
        this.editableTabsValue = activeName;
        this.editableTabs = tabs.filter(tab => tab.name !== targetName);
        sessionStorage.setItem("nowTab", JSON.stringify({title: activeLabel, name: activeName}));
        sessionStorage.setItem("nowTabValue", JSON.stringify(activeName));
        this.$router.push(activeName)
      },
      changeTab(item) {
          sessionStorage.setItem("nowTab", JSON.stringify({title: item.label, name: item.name}));
          sessionStorage.setItem("nowTabValue", JSON.stringify(item.name));
          this.$router.push(item.name)
      }
    },
    created() {
      let tab = sessionStorage.getItem("nowTab");
      if(tab) {
        tab = JSON.parse(tab);
        this.editableTabsValue = tab.name;
        this.editableTabs = [{
          title: tab.title,
          name: tab.name
        }]
      } else {
        // 如果有首页权限，登陆后默认展示首页
        const per = sessionStorage.getItem("permissions");
        if (per) {
          let perList = JSON.parse(per);
          if (perList.findIndex(e => e.menuPath === "/home") !== -1) {
            if (this.editableTabs.findIndex(e => e === {title:"首页",name: "/home"}) === -1) {
              this.editableTabsValue = "/home";
              this.editableTabs = [{
                title: "首页",
                name: "/home"
              }]
            }
          }
        }
      }
    }

}
</script>

<style scoped>
.el-tabs {
  border: 1px solid #c6ded7;
}
</style>
